import { reactive, toRaw } from 'vue'

// 分页钩子函数
export function usePaging(options) {
    const { page = 1, size = 10, fetchFun, params = {}, firstLoading = false } = options
    
    // 记录分页初始参数
    const paramsInit = Object.assign({}, toRaw(params))
    // 分页数据
    const pager = reactive({
        page,
        size,
        loading: firstLoading,
        count: 0,
        lists: [],
        extend: {}
    })
    // console.log(999,pager)
    // 请求分页接口
    const getLists = () => {
        pager.loading = true
        return fetchFun({
            page: pager.page,
            page_size: pager.size,
            ...params
        })
            .then((res) => {
                pager.count = res?.data.total
                pager.lists = res?.data.data
                pager.extend = res?.extend
                return Promise.resolve(res)
            })
            .catch((err) => {
                return Promise.reject(err)
            })
            .finally(() => {
                pager.loading = false
            })
    }
    // 重置为第一页
    const resetPage = () => {
        pager.page = 1
        getLists()
    }
    // 重置参数
    const resetParams = () => {
        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item]
        })
        getLists()
    }
    return {
        pager,
        getLists,
        resetParams,
        resetPage
    }
}
